﻿using BSChuangXu.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BSChuangXu.Infrastructure.Implement
{
    /// <summary>
    /// 实现仓储接口
    /// </summary>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        public readonly BSDbContext db;
        public BaseRepository(BSDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">添加信息</param>
        /// <returns></returns>
        public async Task<int> Add(T entity)
        {
            db.Set<T>().Add(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 添加（批量）
        /// </summary>
        /// <param name="entitys">添加信息</param>
        /// <returns></returns>
        public async Task<int> AddRanges(List<T> entitys)
        {
            db.Set<T>().AddRange(entitys);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<T>> GetAll()
        {
            return  db.Set<T>();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">修改信息</param>
        /// <returns></returns>
        public async Task<int> Update(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 修改（批量）
        /// </summary>
        /// <param name="entitys">修改信息</param>
        /// <returns></returns>
        public async Task<int> UpdateRanges(List<T> entitys)
        {
            db.Set<T>().UpdateRange(entitys);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">删除信息</param>
        /// <returns></returns>
        public async Task<int> Delete(T entity)
        {
            db.Set<T>().Remove(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 删除（批量）
        /// </summary>
        /// <param name="entitys">删除信息</param>
        /// <returns></returns>
        public async Task<int> DeleteRanges(List<T> entitys)
        {
            db.Set<T>().RemoveRange(entitys);
            return await db.SaveChangesAsync();
        }
    }
}
